package com.hao.user.app.login;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hao.common.code.ErrorCode;
import com.hao.common.execption.BusinessException;
import com.hao.user.app.mapper.UserMapper;
import com.hao.user.app.model.dto.user.UserLoginRequest;
import com.hao.user.app.model.entity.User;
import org.springframework.data.redis.core.RedisTemplate;

import static com.hao.user.app.constant.RedisConstant.REDIS_PHONE_CODE;

/**
 * @author haoge
 * @version 1.0
 * @date 2023/5/21 22:39
 */
public class EmailLoginStrategy implements LoginStrategy{

    @Override
    public User login(UserLoginRequest userLoginRequest,RedisTemplate<String ,Object> redisTemplate, UserMapper userMapper) {
        String email = userLoginRequest.getEmail();
        String code = userLoginRequest.getCode();

        String o = (String) redisTemplate.opsForValue().get(REDIS_PHONE_CODE + ":" + email);
        if (o == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "验证码已过期");
        }
        if (!code.equals(o)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "验证码不正确");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", email);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        }
        return user;
    }
}
